package com.bjpowernode.config.handler;

import com.bjpowernode.query.UserQuery;
import com.bjpowernode.result.R;
import jakarta.validation.Valid;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常捕获
 *
 */
@RestControllerAdvice //aop, 捕获到异常后，是返回json或者字符串
//@ControllerAdvice //aop，捕获到异常后，要跳转到页面
public class GlobalExceptionHandler {

    /**
     * 当controller抛出异常后，优先进行精确异常匹配，如果匹配不到就往上层的父类异常进行配置
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handException(MethodArgumentNotValidException e) {
        e.printStackTrace();

        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrorList = bindingResult.getFieldErrors();
        StringBuilder stringBuilder = new StringBuilder();
        fieldErrorList.forEach(fieldError -> {
            stringBuilder.append(fieldError.getDefaultMessage()).append(",");
        });
        return R.FAIL(stringBuilder.toString());
    }

    /**
     * 精确匹配DataIntegrityViolationException异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = DataIntegrityViolationException.class)
    public R handException(DataIntegrityViolationException e) {
        e.printStackTrace();
        return R.FAIL("该数据在引用，不能删除");
    }

    /**
     * 如果精确匹配不到异常，就采用父类的Exception异常进行处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public R handException(Exception e) {
        e.printStackTrace();
        return R.FAIL(e.getMessage());
    }
}
